package com.yk.silence.rxretrofitmvp.base.presenter;

import com.yk.silence.rxretrofitmvp.base.model.BaseModel;
import com.yk.silence.rxretrofitmvp.base.view.BaseView;

import java.lang.ref.WeakReference;

/**
 * Presenter的基类
 *
 * @param <V> 视图层
 * @param <M> 数据层
 */
public abstract class BasePresenter<V extends BaseView, M extends BaseModel> implements IBasePresenter<V, M> {

    private M model;
    //弱引用防止内存泄露
    private WeakReference<V> mWeakRef;

    @Override
    public void registerModel(M model) {
        this.model = model;

    }

    @Override
    public void registerView(V view) {
        this.mWeakRef = new WeakReference<V>(view);
    }

    @Override
    public V getView() {
        return mWeakRef == null ? null : mWeakRef.get();
    }

    /**
     * 在Activity或Fragment卸载时调用View结束的方法
     */
    @Override
    public void onDestroy() {
        if (mWeakRef != null) {
            mWeakRef.clear();
            mWeakRef = null;
        }
        onDestroyView();
    }

    /**
     * 销毁视图
     */
    public abstract void onDestroyView();
}
